package com.tju.backend.plugin.t_io_server.handler;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tju.backend.entity.TProduct;
import com.tju.backend.entity.TStereoscopicWarehouse;
import com.tju.backend.entity.TWarehousing;
import com.tju.backend.plugin.common.GlobalCall;
import com.tju.backend.plugin.common.Push;
import com.tju.backend.plugin.common.SPPacket;
import com.tju.backend.plugin.common.intf.AbsCommonBsHandler;
import com.tju.backend.utils.result.Result;
import com.tju.backend.utils.result.ResultEnum;
import com.tju.backend.utils.result.ResultUtil;
import com.tju.backend.utils.tool.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.tju.backend.plugin.common.GlobalCall.*;
import static com.tju.backend.plugin.common.GlobalCall.str;


/**
 * 相机信号处理
 *
 * @USER: CLS
 */
@Slf4j
@Component
public class CoreBandDispose extends AbsCommonBsHandler {
    public static void main(String[] args) {
        int number = new Random().nextInt(10*1000);
    }
    /**
     * 处理消息
     */
    @Override
    public void handler(SPPacket packet, String bsBody, ChannelContext channelContext) throws Exception {
        String msg = new String(packet.getBody(), "GBK");
        try {
            Pattern pattern = Pattern.compile("([A-Z]{5})(\\d{3})([A-Z]{3})");
            Matcher matcher = pattern.matcher(msg);
            if (!matcher.matches()) {
                throw new Exception(zhCh.DataFormatError);
            }
            List<TStereoscopicWarehouse> swList = sw.selectStereoscopicWarehouseByBarcode(matcher.group(2));
            Result<Object> data = Optional.ofNullable(swList)
                    //数据要等于2条
                    .filter(s -> s.size() == 2)
                    .map(s -> {
                        int id;
                        TWarehousing ware;
                        //修改状态
                        if (s.get(0).getSterGrid().equals(Constants.GRID_INSIDE) && s.get(0).getStatus() == 0) {
                            //符合里面，状态0
                            s.get(0).setStatus(2L);
                            sw.updateStatusById(s.get(0).getId(), new Date());
                            Integer productId = s.get(0).getProductId();
                            log.info("id" + productId);
                            TProduct tProduct = pr.getProductId(productId);
                            int number = new Random().nextInt(15);
                            TProduct t = new TProduct();
                            t.setWarehouseId(1);
                            t.setProductName(productNameCount[number]);
                            t.setProductCoding(productCodingCount[number]);
                            t.setProductSpecification(productSpecificationCount[number]);
                            t.setProductBrand(productBrandCount[0]);
                            t.setProductColour(productColourCount[number]);
                            t.setProductTexture(productTextureCount[number]);
                            t.setId(productId);
                            if (tProduct != null) {
                                t.setUpdateBy("admin");
                                t.setUpdateTime(new Date());
                                int i = pr.updateById(t);
                                log.info("修改" + i);
                            } else {
                                t.setCreateBy("admin");
                                t.setCreateTime(new Date());
                                int insert = pr.insert(t);
                                log.info("添加" + insert);
                            }
                            //封装入库数据
                            ware = new TWarehousing(msg, msg.substring(8), s.get(0));
                            id = s.get(0).getOid();
                            //todo: 进行PLC发送入库
                            Push.tcpPush(str(s.get(0)));
                            log.info("入仓数据"+ResultUtil.success(ResultEnum.RECEIVE, str(s.get(0)), sw.selectAll(taskWarehousing,t)));
                            //发送到前端
                            Push.push(ResultUtil.success(ResultEnum.RECEIVE, str(s.get(0)), sw.selectAll(taskWarehousing,t)));
                        } else
                            return ResultUtil.error(ResultEnum.SPECIAL, zhCh.TheStorageSpaceIsFull);
                        //插入入仓数据
                        warehousingMapper.insert(ware);
                        //封装订单状态数据
                        List<TStereoscopicWarehouse> swLists = sw.getOrderStatus(id);
                        //封装库位统计数据
                        int total = sw.getTotal();   //总数
                        int num = sw.getUsedNum(); //已用
                        int surplus = total - num; //剩余
                        return ResultUtil.success(ResultEnum.SUCCESS, Constants.jsonObject(ware, total, num, surplus, swLists));
                    })
                    .orElseThrow(() -> new Exception(zhCh.InvalidQRCode));
            if (data != null) {
                Push.push(data);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            Push.push(ResultUtil.error(ResultEnum.SPECIAL, e.getMessage()));
        }

    }

}